<?php
use app\admin\model\Notice;

ini_set('memory_limit','512M');
ini_set('max_execution_time',0);
set_time_limit(0);

/**
 * @Title: ajaxReturn
 * @Description: todo(ajax提交返回状态信息)
 * @param string $info
 * @param url $url
 * @param string $status
 * @author duqiu
 * @date 2016-5-12
 */
function ajaxReturn($info='', $url='', $status='', $data = ''){
    if(!empty($url)){   //操作成功
        $result = array( 'info' => '操作成功', 'status' => 1, 'url' => $url, );
    }else{   //操作失败
        $result = array( 'info' => '操作失败', 'status' => 0, 'url' => '', );
    }
    if(!empty($info)){$result['info'] = $info;}
    if(!empty($status)){$result['status'] = $status;}
    if(!empty($data)){$result['data'] = $data;}
    echo json_encode($result);
    exit();
}

/**
 * @Title: deldir
 * @Description: todo(删除文件-清理缓存)
 * @param string $dir
 * @param string $folder
 * @return boolean
 * @author duqiu
 * @date 2016-5-24
 */
function deldir($dir,$folder='n'){
    //删除当前文件夹下得文件（并不删除文件夹）：
    $dh=opendir($dir);
    while ($file=readdir($dh)) {
        if($file!="." && $file!="..") {
            $fullpath=$dir."/".$file;
            if(!is_dir($fullpath)) {
                unlink($fullpath);
            } else {
                deldir($fullpath,$folder);
            }
        }
    }
    closedir($dh);
    //删除当前文件夹
    if($folder=='y'){
        if(rmdir($dir)){
            return true;
        } else {
            return false;
        }
    }
}

/**
 * @Title: unset_array
 * @Description: todo(删除二维数组中的值)
 * @param string $str
 * @param array $arr
 * @return Array
 * @author duqiu
 * @date 2016-6-19
 */
function unset_array($str,$arr){
    foreach ($arr as $key => $value){
        if ($value === $str){
            unset($arr[$key]);
        }
    }
    return $arr;
}

/**
 * @Title: auto_description
 * @Description: todo(自动获取内容的内容简介)
 * @return string
 * @author duqiu
 * @date 2016-8-21
 */
function auto_description($d, $c){
    if( empty($d) ){
        if( !empty($c) ){
            $c = trimall(strip_tags(htmlspecialchars_decode($c)));   //转换标签-去掉HTML标签
            $c = csubstr($c, 250, '', 0, false);
            $result = $c;
        }else{
            $result = '';
        }
    }else{
        $result = $d;
    }
    return $result;
}

/**
 * @Title: time_line
 * @Description: todo(时间轴)
 * @param int $time
 * @return string
 * @author duqiu
 * @date 2016-6-2
 */
function time_line($time){
    $rtime = $time;
    $time = time () - strtotime($time);

    if($time < 60){
        $str = $time.'秒之前';
    }elseif($time < 60*60){
        $min = floor( $time/60 );
        $str = $min.'分钟前';
    }elseif($time < 60*60*24){
        $h = floor($time/(60*60));
        $str = $h.'小时前 ';
    }elseif($time < 60*60*24*3) {
        $d = floor($time/(60*60*24));
        if ($d == 1)
            $str = $d.'天以前';
            else
                $str = $d.'天以前';
    }else{
        $str = $rtime;
    }
    return $str;
}

/**
 * @Title: trimall
 * @Description: todo(清除字符串中的空格和换行)
 * @param string $str
 * @return string
 * @author duqiu
 * @date 2016-8-21
 */
function trimall($str){
    $qian=array(" ","　","\t","\n","\r");
    $hou=array("","","","","");
    return str_replace($qian,$hou,$str);
}

/**
 * @Title: csubstr
 * @Description: todo(中文字符串截取长度)
 * @param string $str
 * @param int $length
 * @param string $charset
 * @param int $start
 * @param boolean $suffix
 * @return string
 * @author duqiu
 * @date 2016-8-21
 */
function csubstr($str, $length, $charset="", $start=0, $suffix=true) {
    if (empty($charset))
        $charset = "utf-8";

        if (function_exists("mb_substr")) {
            if (mb_strlen($str, $charset) <= $length)
                return $str;
                $slice = mb_substr($str, $start, $length, $charset);
        }else {
            $re['utf-8'] = "/[\x01-\x7f]¦[\xc2-\xdf][\x80-\xbf]¦[\xe0-\xef][\x80-\xbf]{2}¦[\xf0-\xff][\x80-\xbf]{3}/";
            $re['gb2312'] = "/[\x01-\x7f]¦[\xb0-\xf7][\xa0-\xfe]/";
            $re['gbk'] = "/[\x01-\x7f]¦[\x81-\xfe][\x40-\xfe]/";
            $re['big5'] = "/[\x01-\x7f]¦[\x81-\xfe]([\x40-\x7e]¦\xa1-\xfe])/";
            preg_match_all($re[$charset], $str, $match);
            if (count($match[0]) <= $length)
                return $str;
            $slice = join("", array_slice($match[0], $start, $length));
        }
        if ($suffix)
            return $slice . "...";
        return $slice;
}

/**
 * @Title: search_url
 * @Description: todo(搜索的地址)
 * @param string $delparam
 * @return string|unknown
 * @throws
 */
function search_url($delparam){
    //$url_path = $_SERVER['PATH_INFO'];
    $url_path = '';
    $get = input('get.');
    if( isset($get[$delparam]) ){ unset($get[$delparam]); }
    if( isset($get['_pjax'])   ){ unset($get['_pjax']);   }
    if(!empty($get)){
        $paramStr = [];
        foreach ($get as $k=>$v){
            $paramStr[] = $k.'='.$v;
        }
        $paramStrs = implode('&', $paramStr);
        $url_path = $url_path.'?'.$paramStrs;
    }
    return $url_path;
}

/**
 * @Title: table_sort
 * @Description: todo(列表table排序)
 * @param string $param
 * @return string
 * @throws
 */
function table_sort($param){
    //$url_path = $_SERVER['PATH_INFO'];
    $url_path = '';
    $faStr = 'fa-sort';
    $get = input('get.');
    if( isset($get['_pjax']) ){ unset($get['_pjax']); }
    
    if( isset($get['_sort']) ){   //判断是否存在排序字段
        $sortArr = explode(',', $get['_sort']);
        if ( $sortArr[0] == $param ){   //当前排序
            if ($sortArr[1] == 'asc'){
                $faStr = 'fa-sort-asc';
                $sort = 'desc';
            }elseif ($sortArr[1] == 'desc'){
                $faStr = 'fa-sort-desc';
                $sort = 'asc';
            }
            $get['_sort'] = $param.','.$sort;
        }else{   //非当前排序
            $get['_sort'] = $param.',asc';
        }
    }else{
        $get['_sort'] = $param.',asc';
    }
    $paramStr = [];
    foreach ($get as $k=>$v){
        $paramStr[] = $k.'='.$v;
    }
    $paramStrs = implode('&', $paramStr);
    $url_path = $url_path.'?'.$paramStrs;
    return "<a class=\"fa ".$faStr."\" href=\"".$url_path."\"></a>";
}

/**
 * @Title: page_param
 * @Description: todo(分页额外参数)
 * @return array
 * @throws
 */
function page_param(){
    $param = request()->param();
    if (isset($param['_pjax'])){
        unset($param['_pjax']);
    }
    $res['query'] = $param;
    return $res;
}

/**
 * @Title: authcheck
 * @Description: todo(权限节点判断)
 * @param string $rule
 * @param int $uid
 * @param string $relation
 * @param string $t
 * @param string $f
 * @return string
 * @author duqiu
 * @date 2016-5-24
 */
function authcheck($rule, $uid, $relation='or', $t='', $f='noauth'){
    $auth = new \expand\Auth();
    if( $auth->check($rule, $uid, $type=1, $mode='url',$relation) ){
        $result = $t;
    }else{
        $result = $f;
    }
    return $result;
}

/**
 * @Title: authTopBtn
 * @Description: todo(操作按钮权限)
 * @param string $rule
 * @param string $cationType
 * @param string || array $param
 * @return string
 * @author duqiu
 * @date 2016-5-14
 */
function authAction($rule, $cationType='create', $param=''){
    $cationTypes = [
        'tonglian' => "<a class=\"btn-text btn-primary\" href=\"".url($rule, $param)."\">提交到通联</a>",
        'detailprojectmanager' => "<a class=\"btn-text btn-primary\" href=\"".url($rule, $param)."\">查看详情</a>",
        'createorder' => "<a href=\"".url($rule, $param)."\" class=\"btn btn-sm btn-primary\">+ 新增订单</a>",
        'createprojectmanager' => "<a href=\"".url($rule, $param)."\" class=\"btn btn-sm btn-primary\">+ 新增</a>",
        'create' => "<a href=\"".url($rule, $param)."\" class=\"btn btn-sm btn-primary\">+ ".lang('create')."</a>",
        'create_arc' => "<a class=\"btn-text btn-primary\" href=\"".url($rule, $param)."\"> ".lang('create_arc')."</a>",
        'edit' => "<a class=\"btn-text btn-primary\" href=\"".url($rule, $param)."\">".lang('edit')."</a>",
        'delete' => "<a class=\"btn-text btn-danger btn-xs delete-one\" href=\"javascript:void(0);\" data-url=\"".url($rule)."\" data-id=\"".$param."\">".lang('delete')."</a>",
        'delete_all' => "<a class=\"btn btn-sm btn-danger delete-all\" href=\"javascript:void(0);\" data-url=\"".url($rule)."\" ><i class=\"fa fa-trash\"></i> ".lang('delete')."</a>",
        'save' => "<button type=\"submit\" class=\"btn btn-info pull-right submits\" data-loading-text=\"&lt;i class='fa fa-spinner fa-spin '&gt;&lt;/i&gt; ".lang('submit')."\">".lang('submit')."</button>",
        'auth_user' => "<a class=\"btn-text btn-primary btn-xs\" href=\"".url($rule, $param)."\">".lang('auth_user')."</a>",
        'auth_group' => "<a class=\"btn-text btn-primary btn-xs\" href=\"".url($rule, $param)."\">".lang('auth_group')."</a>",
        'agree' => "<a class=\"btn btn-success btn-xs\" onclick=\"return confirm('是否已确认给用户退完款？');\" href=\"".url($rule, $param)."\"><i class=\"fa fa-repeat\"></i> ".lang('agree')."</a>",
        'disagree' => "<a class=\"btn btn-danger btn-xs\" href=\"".url($rule, $param)."\"><i class=\"fa fa-undo\"></i> ".lang('disagree')."</a>",
        'backup' => "<a class=\"btn btn-primary btn-sm delete-all\" href=\"javascript:void(0);\" data-url=\"".url($rule)."\" data-title=\"".lang('backup')."\"><i class=\"fa fa-save\"></i> ".lang('backup')."</a>",
        'restore' => "<a class=\"btn btn-primary btn-xs delete-one\" href=\"javascript:void(0);\" data-url=\"".url($rule)."\" data-id=\"".$param."\" data-title=\"".lang('restore')."\"><i class=\"fa fa-rotate-left\"></i> ".lang('restore')."</a>",
        'dowonload' => "<a class=\"btn btn-warning btn-xs\" href=\"".url($rule, $param)."\"><i class=\"fa fa-download\"></i> ".lang('dowonload')."</a>",
        'tokenapi' => "<a class=\"btn btn-danger btn-xs delete-one\" href=\"javascript:void(0);\" data-url=\"".url($rule)."\" data-id=\"".$param."\" data-title=\"".lang('tokenapi')."\"><i class=\"fa fa-lock\"></i> ".lang('tokenapi')."</a>",
        'generate_document' => "<a class=\"btn btn-danger btn-xs delete-one\" href=\"javascript:void(0);\" data-url=\"".url($rule)."\" data-id=\"".$param."\" data-title=\"".lang('generate_document')."\"><i class=\"fa fa-book\"></i> ".lang('generate_document')."</a>",
        'view_document' => "<a class=\"btn btn-warning btn-xs\" href=\"".url($rule, $param)."\"><i class=\"fa fa-book\"></i> ".lang('view_document')."</a>",
        'recharge' => "<a class=\"btn btn-warning btn-xs\" href=\"".url($rule, $param)."\"><i class=\"fa fa-money\"></i> ".lang('recharge')."</a>",
        'Pyes' => "<a class=\"btn-text btn-success delete-one\" href=\"javascript:void(0);\" data-url=\"".url($rule)."\" data-id=\"".$param."\" data-title=\"放款\">放款</a>",
        'Pno' => "<a class=\"btn-text btn-danger delete-one\" href=\"javascript:void(0);\" data-url=\"".url($rule)."\" data-id=\"".$param."\" data-title=\"返本金\">返本金</a>",
        'addcompany' => "<a href=\"".url($rule, $param)."\" class=\"btn btn-sm btn-primary\">+ 添加公司</a>",
        'crecontract' => "<a href=\"".url($rule, $param)."\" class=\"btn btn-sm btn-primary\"><i class=\"fa fa-save\"></i>可视化合同生成</a>",
        'deletecom' => "<a class=\"btn-text btn-danger btn-xs delete-one\" href=\"javascript:void(0);\" data-url=\"".url($rule)."\" data-id=\"".$param."\">".lang('delete')."</a>",
        'deleteht' => "<a class=\"btn-text btn-danger btn-xs delete-one\" href=\"javascript:void(0);\" data-url=\"".url($rule)."\" data-id=\"".$param."\">".lang('delete')."</a>",
    ];
    if( authcheck($rule, UID) != 'noauth' ){
        $result = $cationTypes[$cationType];
    }else{
        $result = '';
    }
    return $result;
}

/**
 * 生成订单号
 * @param string $lenth 长度
 * @return string 字符串
 */
function create_order()
{
    return random(12, '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ').time();
}
/*
*
*@ 随机生成字符串
*/
function random($length, $chars = '0123456789')
{
    $hash = '';
    $max = strlen($chars) - 1;
    for ($i = 0; $i < $length; $i++) {
        $hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}

function Pstatus(){
	return [
		'0' => '待审核',
		'1' => '预热中',
		'2' => '认投中',
		'3' => '待放款',
		'4' => '待还款',
		'5' => '待兑付',
		'6' => '已兑付',
		'-1' => '已失败',
		'-2' => '已拒绝'
	];
}


//通知信息
function TobeNotice($uid,$title,$content){
	$Model = new Notice();
	$data = [
		'uid' => $uid,
		'create_time' => time(),
		'title' => $title,
		'content' => $content
	];
	$Model->insert($data);
}


/**
 * 企业端通知
 * @author hey_heyang(635870453@qq.com)
 */
function companyTobeNotice($uid,$title,$content){
    $Model = new Notice();
    $data = [
        'uid' => $uid,
        'create_time' => time(),
        'title' => $title,
        'content' => $content,
        'type'=>2
    ];
    $Model->insert($data);
}



function ToPHPEXECL($tableheader,$data,$filename){
	//引入类
	vendor('Classes.PHPExcel');
	$excel = new PHPExcel();
	$letter = array('A','B','C','D','E','F','G','H','I','J','K');
	for($i = 0;$i < count($tableheader);$i++) {
		$excel->getActiveSheet()->setCellValue("$letter[$i]1","$tableheader[$i]");
	}
	for ($i = 2;$i <= count($data) + 1;$i++) {
		$j = 0;
		foreach ($data[$i - 2] as $key=>$value) {
			$excel->getActiveSheet()->setCellValue("$letter[$j]$i","$value");
			$j++;
		}
	}
	$write = new PHPExcel_Writer_Excel5($excel);
	header("Pragma: public");
	header("Expires: 0");
	header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
	header("Content-Type:application/force-download");
	header("Content-Type:application/vnd.ms-execl");
	header("Content-Type:application/octet-stream");
	header("Content-Type:application/download");;
	header('Content-Disposition:attachment;filename="'.$filename.'.xls"');
	header("Content-Transfer-Encoding:binary");
	$write->save('php://output');
}
/**
 *数字金额转换成中文大写金额的函数
 *String Int $num 要转换的小写数字或小写字符串
 *return 大写字母
 *小数位为两位
 **/
function rmb($num){
    $c1 = "零壹贰叁肆伍陆柒捌玖";
    $c2 = "分角元拾佰仟万拾佰仟亿";
    //精确到分后面就不要了，所以只留两个小数位
    $num = round($num, 2);
    //将数字转化为整数
    $num = $num * 100;
    if (strlen($num) > 10) {
        return false;
    }
    $i = 0;
    $c = "";
    while (1) {
        if ($i == 0) {
            //获取最后一位数字
            $n = substr($num, strlen($num)-1, 1);
        } else {
            $n = $num % 10;
        }
        //每次将最后一位数字转化为中文
        $p1 = substr($c1, 3 * $n, 3);
        $p2 = substr($c2, 3 * $i, 3);
        if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) {
            $c = $p1 . $p2 . $c;
        } else {
            $c = $p1 . $c;
        }
        $i = $i + 1;
        //去掉数字最后一位了
        $num = $num / 10;
        $num = (int)$num;
        //结束循环
        if ($num == 0) {
            break;
        }
    }
    $j = 0;
    $slen = strlen($c);
    while ($j < $slen) {
        //utf8一个汉字相当3个字符
        $m = substr($c, $j, 6);
        //处理数字中很多0的情况,每次循环去掉一个汉字“零”
        if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') {
            $left = substr($c, 0, $j);
            $right = substr($c, $j + 3);
            $c = $left . $right;
            $j = $j-3;
            $slen = $slen-3;
        }
        $j = $j + 3;
    }
    //这个是为了去掉类似23.0中最后一个“零”字
    if (substr($c, strlen($c)-3, 3) == '零') {
        $c = substr($c, 0, strlen($c)-3);
    }
    //将处理的汉字加上“整”
    if (empty($c)) {
        return "零元整";
    }else{
        return $c . "整";
    }
}

/**
 * 数组去重（去除相同键名）
 * array $arr 要去重的数组
 * string $key 去重的键名
 * return array
 **/
function assoc_unique($arr, $key) {
    $tmp_arr = array();
    foreach ($arr as $k => $v) {
        if (in_array($v[$key], $tmp_arr)) {//搜索$v[$key]是否在$tmp_arr数组中存在，若存在返回true
            unset($arr[$k]);
        } else {
            $tmp_arr[] = $v[$key];
        }
    }
    sort($arr); //sort函数对数组进行排序
    return $arr;
}

/**
 *后台企业端文件下载
 * @author hey_heyang(635870453@qq.com)
 */
 function downLoad($id,$fileName,$routeType=1){
    $file_lj = str_replace("\\","/",ROOT_PATH.'public');
    if($routeType==2){
        $file_dir = $file_lj . '/' . 'uploads' . '/firmProject/' .$id.'/'.$fileName;    // 下载文件存放目录
    }else{
        $file_dir = $file_lj . '/' . 'uploads' . '/projectuser/' .$id.'/'.$fileName;    // 下载文件存放目录
    }

    if (! file_exists($file_dir) ) {
        die('文件未找到');
    }else{
        // 打开文件
        $file1 = fopen($file_dir, "r");
        // 输入文件标签
        Header("Content-type: application/octet-stream");
        Header("Accept-Ranges: bytes");
        Header("Accept-Length:".filesize($file_dir));
        Header("Content-Disposition: attachment;filename=" . $fileName);
        ob_clean();
        flush();
        echo fread($file1, filesize($file_dir));
        fclose($file1);
        exit();
    }

     //通知信息
     function TobeNotice2($user_id,$title,$content){
         $Model = new Notice();
         $data = [
             'uid' => $user_id,
             'create_time' => time(),
             'title' => $title,
             'content' => $content
         ];
         $Model->insert($data);
     }

}